<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>订单列表</span>
      </div>
    </template>

    <div>
      <el-form inline>
        <el-form-item label="房源">
          <el-input v-model="searchForm.hostName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="客户">
          <el-input v-model="searchForm.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.state">
            <el-option label="待确认" value="1"></el-option>
            <el-option label="待支付" value="2"></el-option>
            <el-option label="待入住" value="3"></el-option>
            <el-option label="已完成" value="4"></el-option>
            <el-option label="已退订" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入住时间">
          <el-date-picker
            type="daterange"
            v-model="searchForm.inTime"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="退房时间">
          <el-date-picker
            type="daterange"
            v-model="searchForm.outTime"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div
        style="
          width: 100%;
          padding-bottom: 20px;
          display: flex;
          justify-content: flex-end;
        "
      >
        <el-button type="primary" @click="searchSubmit">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 列表 -->
    <VTable
      :tableData="tableData"
      :options="options"
      @getSelection="handleSelection"
    >
      <template #menubtn>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="warning" @click="handleBatchDelete"
          >批量删除</el-button
        >

        <el-dropdown style="margin-left: 10px">
          <el-button type="success">导出</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleExport(1)"
                >导出行</el-dropdown-item
              >
              <el-dropdown-item @click="handleExport(2)"
                >导出全部</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>

      <template #operate="scope">
        <el-button
          size="small"
          link
          type="primary"
          :icon="View"
          @click="handleDetail(scope.row)"
          >查看</el-button
        >
        <el-button
          size="small"
          link
          type="primary"
          :icon="Edit"
          @click="handleEdit(scope.row)"
          >编辑</el-button
        >
        <el-button
          size="small"
          link
          type="danger"
          :icon="Delete"
          @click="handleDelete(scope.row.id)"
          >删除</el-button
        >
      </template>
    </VTable>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      style="width: 600px"
    >
      <!-- 新增/编辑 -->
      <el-form
        v-if="actionType === '新增' || actionType === '编辑'"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item
          v-for="item in filterOptions"
          :key="item"
          :label="item.label"
          :prop="item.prop"
        >
          <el-autocomplete
            v-if="item.prop === 'title'"
            v-model="ruleForm[item.prop]"
            :fetch-suggestions="querySearchHomestay"
            clearable
            class="inline-input w-50"
            @select="handleSelectHomestay"
            placeholder="请输入房源"
          />
          <el-autocomplete
            v-else-if="item.prop === 'username'"
            v-model="ruleForm[item.prop]"
            :fetch-suggestions="querySearchUsername"
            clearable
            class="inline-input w-50"
            @select="handleSelectUsername"
            placeholder="请输入房客"
          />
          <el-date-picker
            v-else-if="item.prop === 'inTime'"
            v-model="ruleForm[item.prop]"
            type="date"
            placeholder="请选择入住时间"
          />
          <el-date-picker
            v-else-if="item.prop === 'outTime'"
            v-model="ruleForm[item.prop]"
            type="date"
            placeholder="请选择退房时间"
          />
          <el-select
            v-else-if="item.prop === 'state'"
            v-model="ruleForm[item.prop]"
          >
            <el-option :value="1" label="待确认"></el-option>
            <el-option :value="2" label="待付款"></el-option>
            <el-option :value="3" label="待入住"></el-option>
            <el-option :value="4" label="已完成"></el-option>
            <el-option :value="5" label="已退订"></el-option>
          </el-select>
          <el-input-number
            v-else-if="item.prop === 'people'"
            v-model="ruleForm[item.prop]"
            :min="1"
          ></el-input-number>

          <el-input v-else v-model="ruleForm[item.prop]"></el-input>
        </el-form-item>
      </el-form>

      <!-- 详情 -->
      <Description
        v-if="actionType === '查看'"
        :options="options"
        :dataItem="dataItem"
      >
      </Description>
      <template #footer>
        <el-button
          v-if="actionType === '新增' || actionType === '编辑'"
          @click="resetForm(ruleFormRef)"
          >关闭</el-button
        >
        <el-button v-if="actionType === '查看'" @click="dialogVisible = false"
          >关闭</el-button
        >
        <el-button
          v-if="actionType === '新增' || actionType === '编辑'"
          type="primary"
          @click="submitForm(ruleFormRef)"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import {
  getAllOrder,
  deleteOrder,
  batchDeleteOrder,
  searchOrder,
  addOrder,
  updateOrder,
} from "../../api/orderManage/index";
import VTable from "../../components/VTable/index.vue";
import { Delete, Edit, View, Plus, List } from "@element-plus/icons-vue";
import type {
  FormInstance,
  FormRules,
  UploadProps,
  UploadFile,
} from "element-plus";
import Description from "../../components/Description/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getUserList, searchUser } from "../../api/userManage/index";
import {
  getAllHomestay,
  searchHomestayByTitle,
} from "../../api/homestayManage/index";
import { exportExcel } from "../../util/exportUtil";

const tableData = ref<any>([]);
const options = [
  {
    prop: "title",
    label: "房源",
    isTable: true,
    width: 240,
    isForm: true,
  },
  {
    prop: "username",
    label: "客户",
    isTable: true,
    isForm: true,
    type: "autocomplete",
  },
  {
    prop: "inTime",
    label: "入住时间",
    isTable: true,
    type: "date",
    width: 200,
    isForm: true,
  },
  {
    prop: "outTime",
    label: "退房时间",
    isTable: true,
    type: "date",
    width: 200,
    isForm: true,
  },
  {
    prop: "dayCount",
    label: "天数",
    isTable: true,
  },
  {
    prop: "state",
    label: "状态",
    isTable: true,
    width: 100,
    isForm: true,
  },
  {
    prop: "orderNumber",
    label: "订单号",
    isTable: true,
    width: 240,
  },
  {
    prop: "people",
    label: "人数",
    isTable: true,
    isForm: true,
  },
  {
    prop: "totalPrice",
    label: "总价（元）",
    isTable: true,
    width: 120,
  },

  {
    prop: "createTime",
    label: "创建时间",
    type: "time",
  },
];
const filterOptions = options.filter((item) => item.isForm == true);

const dialogTitle = ref("查看"); // 弹出层标题
const dialogVisible = ref<boolean>(false);
const actionType = ref(""); // 操作按钮的类型
const setDialogTile = (type: string) => {
  dialogTitle.value = type;
  actionType.value = type;
  dialogVisible.value = true;
};
//详情
const dataItem = ref<object>({});
const handleDetail = (scope: any) => {
  dataItem.value = scope;
  setDialogTile("查看");
  console.log(dataItem);
};
//删除
const handleDelete = async (id: number) => {
  ElMessageBox.confirm("确认删除此项数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      console.log(id);
      const res = await deleteOrder(id);
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
//子组件传值--多选
const selectData = ref<any>([]);
const ids = ref<any>([]);
const handleSelection = (val: any) => {
  console.log("子组件传值：", val);
  selectData.value.push(val);
  console.log("selectData.value", selectData.value);

  const selecction: any = [];
  val.forEach((item: any) => {
    selecction.push(item.id);
  });
  ids.value = selecction;
  console.log("ids.value:", ids.value);
};
// 批量删除
const handleBatchDelete = async () => {
  if (ids.value.length == 0) {
    ElMessage({
      type: "info",
      message: "请选择数据",
    });
    return;
  }
  ElMessageBox.confirm("确认删除这些数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await batchDeleteOrder(ids.value);
      if (res.data.success) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//搜索
const searchForm = ref<any>({
  username: "",
  hostName: "",
  inTime: Date,
  outTime: Date,
  state: "",
});
const searchSubmit = async () => {
  const res = await searchOrder(searchForm.value);
  tableData.value = res.data.data;
};
//重置
const resetSearch = async () => {
  searchForm.value = {
    username: "",
    hostName: "",
    inTime: Date,
    outTime: Date,
    state: "",
  };
  await onLoad();
};
//新增/编辑
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  title: [{ required: true, message: "请输入房源", trigger: "blur" }],
  inTime: [
    {
      required: true,
      message: "请输入入住时间",
      trigger: "change",
    },
  ],
  outTime: [
    {
      required: true,
      message: "请输入退房时间",
      trigger: "change",
    },
  ],
  dayCount: [{ required: true, message: "请输入天数", trigger: "blur" }],
  people: [{ required: true, message: "请输入人数", trigger: "blur" }],
  state: [{ required: true, message: "请选择状态", trigger: "blur" }],
});
let ruleForm = reactive({
  userId: "",
  houseId: "",
  inTime: Date,
  outTime: Date,
  people: 1,
  state: "",
  price: Number,
});
//新增
const handleAdd = () => {
  ruleForm = reactive({
    userId: "",
    houseId: "",
    inTime: Date,
    outTime: Date,
    people: 1,
    state: "",
    price: Number,
  });
  setDialogTile("新增");
};
//自动补全
const querySearchUsername = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchUser({ username: name });
    res.data.data.forEach((item: any) => {
      list.push({ value: item.username, id: item.id });
    });
  } else {
    const res = await getUserList();
    res.data.data.forEach((item: any) => {
      list.push({ value: item.username, id: item.id });
    });
  }
  callback(list);
};
const querySearchHomestay = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchHomestayByTitle({ title: name });
    res.data.data.forEach((item) => {
      list.push({ value: item.title, id: item.id, price: item.price });
    });
  } else {
    const res = await getAllHomestay();
    res.data.data.forEach((item) => {
      list.push({ value: item.title, id: item.id, price: item.price });
    });
  }
  callback(list);
};
//选中
const handleSelectUsername = (item, $event) => {
  console.log(item);
  ruleForm.userId = item.id;
};
const handleSelectHomestay = (item, $event) => {
  console.log(item);
  ruleForm.houseId = item.id;
  ruleForm.price = item.price;
};
//编辑
const handleEdit = async (scope: any) => {
  ruleForm = scope;
  setDialogTile("编辑");
};
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  console.log(ruleForm);
  if (actionType.value === "新增") {
    const res = await addOrder(ruleForm);

    if (res.data.success == true) {
      ElMessage({
        message: res.data.msg,
        type: "success",
      });
    } else {
      ElMessage.error(res.data.msg);
    }
  } else if (actionType.value === "编辑") {
    const res = await updateOrder(ruleForm);
    if (res.data.success) {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
    }
  }
  onLoad();
  dialogVisible.value = false;
};
//关闭
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if (actionType.value === "新建") {
    formEl.resetFields();
  }
  dialogVisible.value = false;
};

const onLoad = async () => {
  const res = await getAllOrder();
  tableData.value = res.data.data;
};

onMounted(async () => {
  await onLoad();
  console.log(tableData.value);
});

//导出
const handleExport = async (type: number) => {
  const titleArr = [
    "id",
    "房源id",
    "房客id",
    "入住时间",
    "退房时间",
    "天数",
    "人数",
    "总价",
    "创建时间",
    "是否删除",
    "订单状态",
    "订单号",
    "评论",
    "用户名称",
    "房源名称",
    "价格",
  ]; //表头中文名
  if (type === 1) {
    if (selectData.value.length == 0) {
      ElMessage({
        type: "info",
        message: "请选择数据",
      });
      return;
    } else {
      exportExcel(
        selectData.value[selectData.value.length - 1],
        "订单数据表",
        titleArr,
        "sheetName"
      );
    }
  } else {
    exportExcel(tableData.value, "订单数据表", titleArr, "sheetName");
  }
};
</script>

<style></style>
